package com.example.jpatest.service.impl;

import com.example.jpatest.entity.Enter;
import com.example.jpatest.entity.Win;
import com.example.jpatest.repository.EnterRepository;
import com.example.jpatest.repository.RewardRepository;
import com.example.jpatest.repository.WinRepository;
import com.example.jpatest.service.WinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author czx
 */
@Service
public class WinServiceImpl implements WinService {

    @Autowired
    WinRepository winRepository;

    @Autowired
    RewardRepository rewardRepository;

    @Autowired
    EnterRepository enterRepository;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void win(Enter enter, int prize, Win.WinLevel winLevel) {
        Win win = new Win();
        win.setEnter(enter);
        win.setPrize(prize);
        win.setWinLevel(winLevel);
        winRepository.save(win);
        enter.setWin(win);
        enterRepository.save(enter);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void cancelWin(Enter enter) {
        Win win = enter.getWin();
        enter.setWin(null);
        winRepository.delete(win);
    }

    @Override
    public Win getUpdatedWin(Win win,Enter enter) {
        Win w = enter.getWin();
        w.setPrize(win.getPrize());
        w.setWinLevel(win.getWinLevel());
        return w;
    }

    @Override
    public List<Win> getAllWin() {
        return winRepository.findAll();
    }
}
